/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.repair.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.repair.dto.PlanCheckHistoryListDTO;
import org.springblade.modules.repair.dto.PlanTemplateDTO;
import org.springblade.modules.repair.dto.PlanTemplateTypeDTO;
import org.springblade.modules.repair.dto.TemplateTltTreeStrDTO;
import org.springblade.modules.repair.entity.*;
import org.springblade.modules.repair.enums.TaskStatusEnum;
import org.springblade.modules.repair.mapper.MaintainCheckHistoryMapper;
import org.springblade.modules.repair.service.*;
import org.springblade.modules.repair.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 点检内容历史记录 服务实现类
 *
 * @author BladeX
 * @since 2021-05-21
 */
@Service
public class MaintainCheckHistoryServiceImpl extends BaseServiceImpl<MaintainCheckHistoryMapper, MaintainCheckHistory> implements IMaintainCheckHistoryService {

    @Autowired
    @Lazy
    private IMaintainPlanContentService planContentService;
    @Autowired
    private IElevatorService elevatorService;
    @Autowired
    private MaintainPlanConfigService planConfigService;
    @Autowired
    private MaintainTemplateService templateService;
    @Autowired
    private MaintainTemplateContentService templateContentService;
    @Autowired
    private IMaintainPlanTemplateService planTemplateService;
    @Autowired
    private IMaintainTemplateRelationService templateRelationService;
	@Autowired
	private MaintainTemplateLocationTypeService templateLocationTypeService;
	@Autowired
	private IMaintainTemplateHistoryService templateHistoryService;
	@Autowired
	@Lazy
	private PlanHistoryImageService planHistoryImageService;

    @Override
    public IPage<MaintainCheckHistoryVO> selectMaintainCheckHistoryPage(IPage<MaintainCheckHistoryVO> page, MaintainCheckHistoryVO maintainCheckHistory) {
        return page.setRecords(baseMapper.selectMaintainCheckHistoryPage(page, maintainCheckHistory));
    }

    /**
     * @Author lsay
     * @Description {
     * 根据任务id 生成保养每项记录
     * }
     * @Date 9:14 2021/9/26
     * @Param planId 任务id
     **/
    @Override
    public Boolean addHistory(Long planId) {

        MaintainPlanContent planContent = planContentService.getById(planId);
        List<MaintainTemplate> planTemplates = planTemplateService.listPlanTemplate(planId);
        if (ObjectUtil.isEmpty(planTemplates)) {
            throw new ServiceException("工单排期类型已经变更，请重新排期!");
        }
        List<Long> templateIds = planTemplates.stream().map(MaintainTemplate::getId).collect(Collectors.toList());
        // 根据模板id集合获取任务所关联的模板及工作项
        List<PlanTemplateDTO> planTemplateDTOS = templateRelationService.listTemplateContent(templateIds,AuthUtil.getTenantId());
        if (ObjectUtil.isEmpty(planTemplateDTOS)) {
            throw new ServiceException("找不到对应工作项，请联系管理员!");
        }
		// 增加重复校验
		int count = super.count(Wrappers.<MaintainCheckHistory>lambdaQuery().eq(MaintainCheckHistory::getPlanId,planId));
		if(count > 0){
			return Boolean.TRUE;
		}
		List<MaintainTemplateHistory> templateHistories = new ArrayList<>();
		planTemplates.forEach(e -> {
			MaintainTemplateHistory templateHistory = new MaintainTemplateHistory();
			BeanUtil.copyProperties(e,templateHistory, "id","tenantId","createTime","createUser","updateTime","updateUser","createDept","status","isDeleted");
			templateHistory.setPlanId(planId);
			templateHistory.setTemplateId(e.getId());
			templateHistory.setTemplateSceneTypeId(e.getSceneTypeId());
			templateHistory.setTemplateSceneTypeName(e.getSceneTypeName());
			templateHistory.setTemplateSceneTypeDesc(e.getSceneTypeDesc());
			templateHistory.setTenantId(AuthUtil.getTenantId());
			templateHistories.add(templateHistory);
		});
		templateHistoryService.saveBatch(templateHistories);

        List<MaintainCheckHistory> checkHistories = new ArrayList<>();
        planTemplateDTOS.forEach(e -> {
            e.getTemplateContentDTOS().forEach(j -> {
                HashMap<String, String> tltTreeStr = getTltTreeStr(e.getTemplateId(), j.getTltId());
                MaintainCheckHistory checkHistory = new MaintainCheckHistory();
                BeanUtil.copyProperties(j, checkHistory);
				checkHistory.setRequireDesc(j.getRequire());
                checkHistory.setPlanId(planId);
                checkHistory.setElevatorId(planContent.getElevatorId());
                checkHistory.setTemplateId(e.getTemplateId());
                checkHistory.setTemplateName(e.getTemplateName());
                checkHistory.setTemplateSceneTypeId(e.getSceneTypeId());
                checkHistory.setTemplateSceneTypeName(e.getSceneTypeName());
                checkHistory.setTltIds(tltTreeStr.get("tltIdTreeStr"));
                checkHistory.setTltNames(tltTreeStr.get("tltNameTreeStr"));
                checkHistory.setTenantId(AuthUtil.getTenantId());
                checkHistories.add(checkHistory);
            });
        });
        return this.saveBatch(checkHistories);
    }

    /**
     * 处理模板分类冗余数据
     *
     * @param templateId
     * @param tltId
     * @return
     */
    private HashMap<String, String> getTltTreeStr(Long templateId, Long tltId) {
		// 查询指定子节点所有父级 倒序
        List<TemplateLocationTypeTreeVO> templateTltTreeList = templateLocationTypeService.treeDesc(templateId,tltId);
		List<TemplateLocationTypeTreeVO> templateTltList = new ArrayList<>();
		templateTltList = change(templateTltList,templateTltTreeList);
		Collections.reverse(templateTltList);
        String tltIdTreeStr = templateTltList.stream().map(e -> String.valueOf(e.getTltId())).collect(Collectors.joining(","));
        String tltNameTreeStr = templateTltList.stream().map(TemplateLocationTypeTreeVO::getName).collect(Collectors.joining("&&"));
        HashMap<String, String> tltTreeStr = new HashMap<>(2);
        tltTreeStr.put("tltIdTreeStr", tltIdTreeStr);
        tltTreeStr.put("tltNameTreeStr", tltNameTreeStr);
        return tltTreeStr;
    }

	/**
	 * 递归 分类树转集合
	 * @param templateTltList
	 * @param templateTltTreeList
	 * @return
	 */
	private List<TemplateLocationTypeTreeVO> change(List<TemplateLocationTypeTreeVO> templateTltList,List<TemplateLocationTypeTreeVO> templateTltTreeList) {
		templateTltTreeList.forEach(e -> {
			templateTltList.add(e);
			if(ObjectUtil.isNotEmpty(e.getChildren())){
				change(templateTltList,e.getChildren());
			}
		});
		return templateTltList;
	}

	@Override
    public List<MaintainCheckHistoryVO> listCheckHistoryRecord(Long planId, Long locationTypeId) {
        return baseMapper.listCheckHistoryRecord(planId, locationTypeId);
    }

	@Override
	public List<PlanTemplateVO> listPlanHistory(Long planId, Long tltId,Long templateId) {
		return baseMapper.listPlanHistory(planId,tltId,templateId);
	}

	@Override
	public Integer countPlanTemplateTypeContent(Long planId, Long templateId, Long tltId) {
		return baseMapper.countPlanTemplateTypeContent(planId,templateId,tltId);
	}

	@Override
	public List<PlanTemplateContentVO> getPlanWorkItemList(Long planId) {
		return baseMapper.getPlanWorkItemList(planId);
	}

	@Override
	public List<PlanCheckHistoryListDTO> getCheckHistoryList(Long planId) {
		return baseMapper.getCheckHistoryList(planId);
	}

	@Override
	public List<String> getTemplateNames(Long planId) {
		return baseMapper.getTemplateNames(planId).stream().distinct().collect(Collectors.toList());
	}

	@Override
	public List<MaintainCheckHistory> listByPlanId(Long planId) {
		return baseMapper.listByPlanId(planId);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Boolean updateDetail(MaintainCheckHistory maintainCheckHistory) {
		MaintainPlanContent planContent = planContentService.getById(maintainCheckHistory.getPlanId());

		Long userId = AuthUtil.getUserId();
		// 判断工作项内容是否为图片或者视频
		if(Func.isNotEmpty(maintainCheckHistory.getRecordData())){
			if (maintainCheckHistory.getRecordData().containsKey("type") && maintainCheckHistory.getRecordData().getInteger("type").equals(3) || maintainCheckHistory.getRecordData().getInteger("type").equals(4)) {
				MaintainCheckHistory online = baseMapper.selectByCheckHistoryId(maintainCheckHistory.getId());
				JSONArray onlineValOthers = new JSONArray();
				if(online.getRecordData().containsKey("val") && Func.isNotEmpty(online.getRecordData().getJSONArray("val"))){
					JSONArray onlineVal = online.getRecordData().getJSONArray("val");
					for (int i = 0; i < onlineVal.size(); i++) {
						JSONObject v1 = onlineVal.getJSONObject(i);
						if(v1.containsKey("userId") && Func.isNotEmpty(v1.getLong("userId")) && userId != v1.getLongValue("userId")){
							onlineValOthers.add(v1);
						}
					}

					JSONArray offlineValSelf = new JSONArray();
					if(online.getRecordData().containsKey("val") && Func.isNotEmpty(online.getRecordData().getJSONArray("val"))){
						JSONArray offlineVal = maintainCheckHistory.getRecordData().getJSONArray("val");
						for (int i = 0; i < offlineVal.size(); i++) {
							JSONObject v1 = offlineVal.getJSONObject(i);
							if(v1.containsKey("userId") && Func.isNotEmpty(v1.getLong("userId")) && userId == v1.getLongValue("userId")){
								offlineValSelf.add(v1);
							}
						}
					}
					JSONArray val = new JSONArray();
					val.addAll(onlineValOthers);
					val.addAll(offlineValSelf);
					maintainCheckHistory.getRecordData().put("val",val);
				}
			}
		}
		Boolean result = super.updateById(maintainCheckHistory);
		planHistoryImageService.removeByPlan(planContent.getId());
		return result;
	}

}

































